/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tt.cards.User.controller;

import com.tt.cards.User.entity.Wuser;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;

/**
 *
 * @author ylevkovych
 */
@Stateless
@LocalBean
public class WuserEJB implements WuserEJBRemote {

    @PersistenceUnit(unitName="tradethisPU")
    public EntityManagerFactory emf = null;
     
    private EntityManager getEntityManager() {
    	return emf.createEntityManager();
    }
    
    @Override
    public Wuser create(Wuser wuser) throws Exception{
    	EntityManager em = null;
        try {
        	em = getEntityManager();
            em.persist(wuser);
            return wuser;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
        	if(em != null) em.close();
        }
    }

    @Override
    public void delete(Wuser wuser) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Wuser update(Wuser wuser) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Wuser> findAll() {
    	EntityManager em = null;
    	try{
    		em = getEntityManager();
    		Query query =  em.createNativeQuery("SELECT * FROM WUSER", Wuser.class);
            return query.getResultList();
    	} finally {
    		if(em != null) em.close();
    	}
    }

    @Override
    public Wuser findById(Long id) {
    	EntityManager em = null;
    	try{
    		em = getEntityManager();
    		return em.find(Wuser.class, id);
    	} finally {
    		if (em != null) em.close();
    	}
    }
    
    @Override
    public List<Wuser> findByName(String name) {
    	EntityManager em = null;
    	try{
            em = getEntityManager();
            Query query = em.createNativeQuery("SELECT * FROM WUSER AS wuser WHERE wuser.name=?1", Wuser.class);
            query.setParameter("1", name);
            return query.getResultList();
    	} finally {
    		if (em !=  null) em.close();
    	}
    }
    
    @Override
    public Wuser findFirstByName(String name) {
    	EntityManager em = null;
    	try{
            em = getEntityManager();
	    Wuser wuser = null;
	    Query query = em.createNativeQuery("SELECT * FROM WUSER AS wuser WHERE wuser.name=?1", Wuser.class);
            query.setParameter("1", name);
            List<Wuser> wuserList = query.getResultList();
            if(wuserList.size()>0){
                wuser = wuserList.get(0);
            }
            return wuser;
    	} finally {
            if (em != null)	em.close();
    	}
    }
    
}
